<?php
include 'includes/header.php';
require_once '../config/database.php';

if (!is_admin()) {
    redirect('./login.php');
}

if (!isset($_GET['id'])) {
    redirect('/admin/manage_cars.php');
}

$database = new Database();
$db = $database->getConnection();

// Get car details
$query = "SELECT c.*, b.name as brand_name, m.name as model_name 
          FROM cars c 
          LEFT JOIN brands b ON c.brand_id = b.id 
          LEFT JOIN models m ON c.model_id = m.id 
          WHERE c.id = ?";
$stmt = $db->prepare($query);
$stmt->execute([$_GET['id']]);
$car = $stmt->fetch();

if (!$car) {
    redirect('/admin/manage_cars.php');
}

// Get additional images
$images_query = "SELECT * FROM car_images WHERE car_id = ?";
$images_stmt = $db->prepare($images_query);
$images_stmt->execute([$_GET['id']]);
$additional_images = $images_stmt->fetchAll();

// Get all brands
$brands_query = "SELECT * FROM brands ORDER BY name";
$brands = $db->query($brands_query)->fetchAll();

// Get models for selected brand
$models_query = "SELECT * FROM models WHERE brand_id = ? ORDER BY name";
$models_stmt = $db->prepare($models_query);
$models_stmt->execute([$car['brand_id']]);
$models = $models_stmt->fetchAll();

if (isset($_POST['submit'])) {
    $brand_id = $_POST['brand_id'];
    $model_id = $_POST['model_id'];
    $title = sanitize_input($_POST['title']);
    $year = (int)$_POST['year'];
    $price = (float)$_POST['price'];
    $mileage = (int)$_POST['mileage'];
    $fuel_type = $_POST['fuel_type'];
    $transmission = $_POST['transmission'];
    $drive_terrain = $_POST['drive_terrain'];
    $condition_type = $_POST['condition_type'];
    $body_type = $_POST['body_type'];
    $steering = $_POST['steering'];
    $displacement = (int)$_POST['displacement'];
    $model_code = sanitize_input($_POST['model_code']);
    $description = sanitize_input($_POST['description']);
    $features = sanitize_input($_POST['features']);
    $status = $_POST['status'];

    // Handle uploaded and deleted images
    $uploaded_images = json_decode($_POST['uploaded_images'] ?? '[]', true);
    $deleted_images = json_decode($_POST['deleted_images'] ?? '[]', true);
    
    // Delete removed images
    foreach ($deleted_images as $image_name) {
        $image_path = '../uploads/cars/' . $image_name;
        if (file_exists($image_path)) {
            unlink($image_path);
        }
    }
    
    // Update main image if there are new uploads
    if (!empty($uploaded_images)) {
        $main_image = $uploaded_images[0];
        
        // Delete old main image
        if (file_exists('../' . $car['main_image'])) {
            unlink('../' . $car['main_image']);
        }
        
        // Update main image in database
        $update_image = "UPDATE cars SET main_image = ? WHERE id = ?";
        $stmt = $db->prepare($update_image);
        $stmt->execute([$main_image, $car['id']]);
        
        // Add additional images
        if (count($uploaded_images) > 1) {
            $image_query = "INSERT INTO car_images (car_id, image_path) VALUES (?, ?)";
            $image_stmt = $db->prepare($image_query);
            
            // Skip first image as it's already the main image
            for ($i = 1; $i < count($uploaded_images); $i++) {
                $image_stmt->execute([$car['id'], $uploaded_images[$i]]);
            }
        }
    }

    // Update car details
    $query = "UPDATE cars SET 
              brand_id = ?, model_id = ?, title = ?, year = ?, 
              price = ?, mileage = ?, fuel_type = ?, transmission = ?, 
              drive_terrain = ?, condition_type = ?, body_type = ?, steering = ?,
              displacement = ?, model_code = ?, description = ?, features = ?, status = ? 
              WHERE id = ?";
    
    $stmt = $db->prepare($query);
    if ($stmt->execute([
        $brand_id, $model_id, $title, $year, $price, $mileage,
        $fuel_type, $transmission, $drive_terrain, $condition_type,
        $body_type, $steering, $displacement, $model_code,
        $description, $features, $status, $car['id']
    ])) {
        // Handle image deletions
        if (isset($_POST['delete_images'])) {
            foreach ($_POST['delete_images'] as $image_id) {
                $get_image = "SELECT image_path FROM car_images WHERE id = ? AND car_id = ?";
                $stmt = $db->prepare($get_image);
                $stmt->execute([$image_id, $car['id']]);
                $image = $stmt->fetch();

                if ($image && file_exists('../' . $image['image_path'])) {
                    unlink('../' . $image['image_path']);
                }

                $delete_image = "DELETE FROM car_images WHERE id = ? AND car_id = ?";
                $stmt = $db->prepare($delete_image);
                $stmt->execute([$image_id, $car['id']]);
            }
        }

        set_message('Car updated successfully');
        redirect('/admin/manage_cars.php');
    } else {
        set_message('Error updating car', 'danger');
    }
}
?>

<div class="container py-4">
    <div class="row">
        <div class="col-12">
            <h2 class="mb-4">Edit Car</h2>
            
            <div class="card shadow">
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Title</label>
                                <input type="text" class="form-control" name="title" 
                                       value="<?php echo htmlspecialchars($car['title']); ?>" required>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Brand</label>
                                <select name="brand_id" class="form-select" id="brand-select" required>
                                    <option value="">Select Brand</option>
                                    <?php foreach ($brands as $brand): ?>
                                        <option value="<?php echo $brand['id']; ?>" 
                                                <?php echo $brand['id'] == $car['brand_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($brand['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Model</label>
                                <select name="model_id" class="form-select" id="model-select" required>
                                    <option value="">Select Model</option>
                                    <?php foreach ($models as $model): ?>
                                        <option value="<?php echo $model['id']; ?>" 
                                                <?php echo $model['id'] == $car['model_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($model['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-select" required>
                                    <option value="Available" <?php echo $car['status'] === 'Available' ? 'selected' : ''; ?>>Available</option>
                                    <option value="Sold" <?php echo $car['status'] === 'Sold' ? 'selected' : ''; ?>>Sold</option>
                                    <option value="Reserved" <?php echo $car['status'] === 'Reserved' ? 'selected' : ''; ?>>Reserved</option>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Year</label>
                                <select name="year" class="form-select" required>
                                    <?php for($i = date('Y') + 1; $i >= 1990; $i--): ?>
                                        <option value="<?php echo $i; ?>" 
                                                <?php echo $i == $car['year'] ? 'selected' : ''; ?>>
                                            <?php echo $i; ?>
                                        </option>
                                    <?php endfor; ?>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Price</label>
                                <input type="number" class="form-control" name="price" step="0.01" 
                                       value="<?php echo $car['price']; ?>" required>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Mileage</label>
                                <input type="number" class="form-control" name="mileage" 
                                       value="<?php echo $car['mileage']; ?>" required>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Fuel Type</label>
                                <select name="fuel_type" class="form-select" required>
                                    <?php
                                    $fuel_types = ['Petrol', 'Diesel', 'Electric', 'Hybrid'];
                                    foreach ($fuel_types as $type):
                                    ?>
                                        <option value="<?php echo $type; ?>" 
                                                <?php echo $car['fuel_type'] === $type ? 'selected' : ''; ?>>
                                            <?php echo $type; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Transmission</label>
                                <select name="transmission" class="form-select" required>
                                    <?php
                                    $transmissions = ['Manual', 'Automatic', 'CVT'];
                                    foreach ($transmissions as $trans):
                                    ?>
                                        <option value="<?php echo $trans; ?>" 
                                                <?php echo $car['transmission'] === $trans ? 'selected' : ''; ?>>
                                            <?php echo $trans; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Drive Terrain</label>
                                <select name="drive_terrain" class="form-select" required>
                                    <option value="">Select Drive Terrain</option>
                                    <option value="FWD" <?php echo $car['drive_terrain'] == 'FWD' ? 'selected' : ''; ?>>Front Wheel Drive (FWD)</option>
                                    <option value="RWD" <?php echo $car['drive_terrain'] == 'RWD' ? 'selected' : ''; ?>>Rear Wheel Drive (RWD)</option>
                                    <option value="AWD" <?php echo $car['drive_terrain'] == 'AWD' ? 'selected' : ''; ?>>All Wheel Drive (AWD)</option>
                                    <option value="4WD" <?php echo $car['drive_terrain'] == '4WD' ? 'selected' : ''; ?>>Four Wheel Drive (4WD)</option>
                                    <option value="2WD" <?php echo $car['drive_terrain'] == '2WD' ? 'selected' : ''; ?>>Two Wheel Drive (2WD)</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Body Type</label>
                                <select name="body_type" class="form-select" required>
                                    <option value="">Select Body Type</option>
                                    <option value="Sedan" <?php echo $car['body_type'] == 'Sedan' ? 'selected' : ''; ?>>Sedan</option>
                                    <option value="SUV" <?php echo $car['body_type'] == 'SUV' ? 'selected' : ''; ?>>SUV</option>
                                    <option value="Hatchback" <?php echo $car['body_type'] == 'Hatchback' ? 'selected' : ''; ?>>Hatchback</option>
                                    <option value="Coupe" <?php echo $car['body_type'] == 'Coupe' ? 'selected' : ''; ?>>Coupe</option>
                                    <option value="Wagon" <?php echo $car['body_type'] == 'Wagon' ? 'selected' : ''; ?>>Wagon</option>
                                    <option value="Van" <?php echo $car['body_type'] == 'Van' ? 'selected' : ''; ?>>Van</option>
                                    <option value="Truck" <?php echo $car['body_type'] == 'Truck' ? 'selected' : ''; ?>>Truck</option>
                                    <option value="Convertible" <?php echo $car['body_type'] == 'Convertible' ? 'selected' : ''; ?>>Convertible</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Steering</label>
                                <select name="steering" class="form-select" required>
                                    <option value="Left" <?php echo $car['steering'] == 'Left' ? 'selected' : ''; ?>>Left Hand Drive</option>
                                    <option value="Right" <?php echo $car['steering'] == 'Right' ? 'selected' : ''; ?>>Right Hand Drive</option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Engine Displacement (cc)</label>
                                <input type="number" class="form-control" name="displacement" value="<?php echo htmlspecialchars($car['displacement']); ?>" required>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label class="form-label">Model Code</label>
                                <input type="text" class="form-control" name="model_code" value="<?php echo htmlspecialchars($car['model_code']); ?>" placeholder="e.g., E90, W204">
                            </div>

                            <div class="col-12 mb-3">
                                <label class="form-label">Description</label>
                                <textarea class="form-control" name="description" rows="4" required><?php 
                                    echo htmlspecialchars($car['description']); 
                                ?></textarea>
                            </div>

                            <div class="col-12 mb-3">
                                <label class="form-label">Features (one per line)</label>
                                <textarea class="form-control" name="features" rows="4" required><?php 
                                    echo htmlspecialchars($car['features']); 
                                ?></textarea>
                            </div>

                            <!-- Image Upload -->
                            <div class="card shadow mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Car Images</h5>
                                </div>
                                <div class="card-body">
                                    <!-- Current Images Preview -->
                                    <div class="mb-4">
                                        <h6>Current Images</h6>
                                        <div class="row g-3">
                                            <!-- Main Image -->
                                            <div class="col-md-4">
                                                <div class="card">
                                                    <img src="../<?php echo htmlspecialchars($car['main_image']); ?>" 
                                                         class="card-img-top" alt="Main Image"
                                                         style="height: 200px; object-fit: cover;">
                                                    <div class="card-body">
                                                        <p class="card-text text-center">Main Image</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <!-- Additional Images -->
                                            <?php foreach ($additional_images as $image): ?>
                                            <div class="col-md-4">
                                                <div class="card">
                                                    <img src="../<?php echo htmlspecialchars($image['image_path']); ?>" 
                                                         class="card-img-top" alt="Additional Image"
                                                         style="height: 200px; object-fit: cover;">
                                                    <div class="card-body">
                                                        <button type="button" class="btn btn-danger btn-sm w-100 delete-image" 
                                                                data-image-id="<?php echo $image['id']; ?>">
                                                            <i class="fas fa-trash"></i> Remove
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>

                                    <div class="filepond--wrapper">
                                        <input type="file" class="filepond" multiple>
                                    </div>
                                    <input type="hidden" name="uploaded_images" id="uploadedImages">
                                </div>
                            </div>

                            <div class="col-12">
                                <button type="submit" name="submit" class="btn btn-primary">Update Car</button>
                                <a href="/admin/manage_cars.php" class="btn btn-secondary">Cancel</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('brand-select').addEventListener('change', function() {
    const brandId = this.value;
    const modelSelect = document.getElementById('model-select');
    
    if (brandId) {
        fetch(`/get_models.php?brand_id=${brandId}`)
            .then(response => response.json())
            .then(models => {
                modelSelect.innerHTML = '<option value="">Select Model</option>';
                models.forEach(model => {
                    const option = document.createElement('option');
                    option.value = model.id;
                    option.textContent = model.name;
                    modelSelect.appendChild(option);
                });
            });
    } else {
        modelSelect.innerHTML = '<option value="">Select Brand First</option>';
    }
});

FilePond.registerPlugin(
    FilePondPluginImagePreview,
    FilePondPluginFileValidateType
);

// Initialize FilePond
const pond = FilePond.create(document.querySelector('.filepond'), {
    files: [
        // Add main image
        {
            source: '<?php echo $car['main_image']; ?>',
            options: {
                type: 'local'
            }
        },
        // Add additional images
        <?php foreach ($additional_images as $image): ?>
        {
            source: '<?php echo $image['image_path']; ?>',
            options: {
                type: 'local'
            }
        },
        <?php endforeach; ?>
    ],
    allowMultiple: true,
    maxFiles: 10,
    allowReorder: true,
    instantUpload: true,
    acceptedFileTypes: ['image/*'],
    labelFileProcessingComplete: 'Upload complete',
    labelFileProcessingError: 'Upload failed',
    server: {
        process: {
            url: 'upload_image.php',
            method: 'POST',
            onload: (response) => {
                try {
                    const data = JSON.parse(response);
                    console.log('Upload response:', data);
                    if (data.success) {
                        const uploadedImages = JSON.parse(document.getElementById('uploadedImages').value || '[]');
                        uploadedImages.push(data.path);
                        document.getElementById('uploadedImages').value = JSON.stringify(uploadedImages);
                        console.log('Updated images list:', uploadedImages);
                        return data.path;
                    }
                    console.error('Upload failed:', data.message);
                    return null;
                } catch (e) {
                    console.error('Parse error:', e, response);
                    return null;
                }
            }
        },
        revert: {
            url: 'delete_image.php',
            method: 'POST'
        }
    }
});

// Handle form submission
document.querySelector('form').addEventListener('submit', function(e) {
    const uploadedImages = JSON.parse(document.getElementById('uploadedImages').value || '[]');
    const existingImages = pond.getFiles()
        .filter(file => file.origin === 1)
        .map(file => file.serverId);
    
    if (uploadedImages.length === 0 && existingImages.length === 0) {
        alert('Please upload at least one image');
        e.preventDefault();
        return false;
    }
    
    if (!this.checkValidity()) {
        e.preventDefault();
        this.reportValidity();
        return false;
    }
    
    document.getElementById('uploadedImages').value = JSON.stringify([...existingImages, ...uploadedImages]);
    return true;
});
</script>

<style>
.filepond--root {
    max-height: 400px;
}
.filepond--panel-root {
    background-color: #f8f9fa;
    border: 2px dashed #dee2e6;
}
.filepond--drop-label {
    color: #6c757d;
}
.filepond--item-panel {
    background-color: #e9ecef;
}
.filepond--image-preview-wrapper {
    border-radius: 8px;
}
</style>

<?php include 'includes/footer.php'; ?> 